﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using System.Transactions;
using PaperSystem.Models;

namespace PaperSystem.Models
{
    public class QuestionRepository
    {
        PaperDatabaseEntities db;

        public QuestionRepository()
        {
            db = new PaperDatabaseEntities();
        }

        //根据信息获取题目显示列表
        public List<QuestionList> GetQuestionList(QuestionQuery info)
        {
            var list = (from a in db.Ex_question
                        select new QuestionList()
                        {
                            chapter = a.Chapter,
                            content = a.Econtent,
                            course = a.Course.Cname,
                            creator = a.Teacher.Tname,
                            eid = a.Eid,
                            knowledge = a.Knowledge,
                            time = a.Etime,
                            TorE = a.TorE,
                            type = a.Etype,
                            cited = a.Cited
                        });
            if (info != null)
            {
                if (info.course != null)
                {
                    list = list.Where(a => a.course == info.course);
                }
                if (info.type != null)
                {
                    list = list.Where(a => a.type == info.type);
                }
                if (info.chapter != null)
                {
                    list = list.Where(a => a.chapter.Contains(info.chapter));
                }
                if (info.creator != null)
                {
                    list = list.Where(a => a.creator.Contains(info.creator));
                }
                if (info.knowledge != null)
                {
                    list = list.Where(a => a.knowledge.Contains(info.knowledge));
                }
            }
            return list.ToList();
        }

        //根据教师id返回用户名
        public string TeacherName(string id)
        {
            string username = "";
            try
            {            
                var tempdata = db.Teacher.Where(t => t.Tid == id).FirstOrDefault();
                username = tempdata.Tname;
            }
            catch (Exception e)
            {
            }

            return username;
        }

        //返回所有课程名称
        public SelectList GetCourse()
        {
            var list = db.Course.ToList();
            List<SelectListItem> listItem = new List<SelectListItem>();
            foreach (var a in list)
            {
                listItem.Add(new SelectListItem { Text = a.Cname, Value = a.Cname });
            }
            return new SelectList(listItem, "Value", "Text", "");
        }

        //返回所有课程名称，有默认选中值
        public SelectList GetCourse(string selected)
        {
            var list = db.Course.ToList();
            List<SelectListItem> listItem = new List<SelectListItem>();
            foreach (var a in list)
            {
                listItem.Add(new SelectListItem { Text = a.Cname, Value = a.Cname });
            }
            return new SelectList(listItem, "Value", "Text", selected);
        }

        //创建题目类型下拉框的内容
        public SelectList GetType()
        {
            //TODO：内容待定
            List<SelectListItem> listItem = new List<SelectListItem>();
            listItem.Add(new SelectListItem { Text = "阅读理解", Value = "阅读理解" });
            listItem.Add(new SelectListItem { Text = "完形填空", Value = "完形填空" });
            listItem.Add(new SelectListItem { Text = "翻译", Value = "翻译" });
            listItem.Add(new SelectListItem { Text = "作文", Value = "作文" });
            listItem.Add(new SelectListItem { Text = "综合选择", Value = "综合选择" });
            listItem.Add(new SelectListItem { Text = "词语搭配", Value = "词语搭配" });
            SelectList list = new SelectList(listItem, "Value", "Text");
            return list;
        }

        //创建题目类型下拉框的内容，有默认选中值
        public SelectList GetType(string selected)
        {
            //TODO：内容待定
            List<SelectListItem> listItem = new List<SelectListItem>();
            listItem.Add(new SelectListItem { Text = "阅读理解", Value = "阅读理解" });
            listItem.Add(new SelectListItem { Text = "完形填空", Value = "完形填空" });
            listItem.Add(new SelectListItem { Text = "翻译", Value = "翻译" });
            listItem.Add(new SelectListItem { Text = "作文", Value = "作文" });
            listItem.Add(new SelectListItem { Text = "综合选择", Value = "综合选择" });
            listItem.Add(new SelectListItem { Text = "词语搭配", Value = "词语搭配" });
            SelectList list = new SelectList(listItem, "Value", "Text", selected);
            return list;
        }

        //添加题目
        public bool InsertQuestion(NewExQuestion exQuestion, NewInQuestion[] inQuestion)
        {
            Ex_question exq = new Ex_question();//注意这些对象每用一次就要new一次
            In_question inq;
            Fill inqFill;
            Choice inqChoice;
            Judge inqJudge;
            QnA inqQna;
            try
            {
                //给总试题索引表的对象赋值
                exq.Teacher = db.Teacher.Where(a => a.Tid == exQuestion.creatorId).FirstOrDefault();
                exq.Etime = exQuestion.time;
                exq.Course = db.Course.Where(a => a.Cname == exQuestion.course).FirstOrDefault();
                exq.Econtent = exQuestion.content;
                exq.Etype = exQuestion.type;
                exq.Enum = exQuestion.includeNum;
                exq.Chapter = exQuestion.chapter;
                exq.Knowledge = exQuestion.knowledge;
                exq.TorE = exQuestion.TorE;
                exq.Cited = 0;//新增题目被引用次数为0
                db.AddToEx_question(exq);
                db.SaveChanges();
                if (inQuestion != null)
                {
                    foreach (var question in inQuestion)
                    {
                        //给小试题索引表的对象赋值
                        inq = new In_question();
                        inq.Ex_question = exq;
                        inq.Iorder = question.Iorder;
                        inq.Answer_mode = question.answerMode;
                        db.AddToIn_question(inq);
                        db.SaveChanges();
                        //给具体题型的对象赋值
                        if (question.answerMode == "选择题")
                        {
                            inqChoice = new Choice();
                            //inqChoice.In_question = new In_question();不要new一个，不然会新增
                            inqChoice.In_question = inq;
                            inqChoice.Answer = question.answer;
                            inqChoice.Ccontent = question.Icontent;
                            inqChoice.Issingle = question.isSingle;
                            inqChoice.Option1 = question.option1;
                            inqChoice.Option2 = question.option2;
                            inqChoice.Option3 = question.option3;
                            inqChoice.Option4 = question.option4;
                            inqChoice.Option5 = question.option5;
                            inqChoice.Option6 = question.option6;
                            inqChoice.Option7 = question.option7;
                            inqChoice.Option8 = question.option8;
                            inqChoice.optionNum = question.optionNum;
                            db.AddToChoice(inqChoice);
                            db.SaveChanges();
                        }
                        else if (question.answerMode == "填空题")
                        {
                            inqFill = new Fill();
                            inqFill.In_question = inq;
                            inqFill.Fcontent = question.Icontent;
                            inqFill.Answer = question.answer;
                            db.AddToFill(inqFill);
                            db.SaveChanges();
                        }
                        else if (question.answerMode == "判断题")
                        {
                            inqJudge = new Judge();
                            inqJudge.In_question = inq;
                            inqJudge.Jcontent = question.Icontent;
                            inqJudge.Answer = question.answer;
                            db.AddToJudge(inqJudge);
                            db.SaveChanges();
                        }
                        else if (question.answerMode == "回答问题")
                        {
                            inqQna = new QnA();
                            inqQna.In_question = inq;
                            inqQna.Answer = question.answer;
                            inqQna.Qcontent = question.Icontent;
                            db.AddToQnA(inqQna);
                            db.SaveChanges();
                        }
                    }
                }
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }

        //删除题目（删除一整题）
        public bool DeleteQuestion(string eidString)
        {
            try
            {
                //处理接收到的eid字符串
                string[] eidArray1 = eidString.Split(' ');
                int[] eidArray2 = new int[eidArray1.Count()];
                for (int i = 0; i < eidArray1.Count(); i++)
                {
                    eidArray2[i] = Convert.ToInt32(eidArray1[i]);
                }
                foreach (int eid in eidArray2)
                {
                    var exq = db.Ex_question.Where(a => a.Eid == eid).ToList();
                    var inq = db.In_question.Where(a => a.Ex_question.Eid == eid).ToList();
                    var choice = db.Choice.Where(a => a.In_question.Ex_question.Eid == eid).ToList();
                    var fill = db.Fill.Where(a => a.In_question.Ex_question.Eid == eid).ToList();
                    var judge = db.Judge.Where(a => a.In_question.Ex_question.Eid == eid).ToList();
                    var qna = db.QnA.Where(a => a.In_question.Ex_question.Eid == eid).ToList();
                    using (TransactionScope scope = new TransactionScope())
                    {
                        if (choice.Count() > 0)
                        {
                            foreach (var temp in choice)
                            {
                                db.DeleteObject(temp);
                            }
                        }
                        if (fill.Count() > 0)
                        {
                            foreach (var temp in fill)
                            {
                                db.DeleteObject(temp);
                            }
                        }
                        if (judge.Count() > 0)
                        {
                            foreach (var temp in judge)
                            {
                                db.DeleteObject(temp);
                            }
                        }
                        if (qna.Count() > 0)
                        {
                            foreach (var temp in qna)
                            {
                                db.DeleteObject(temp);
                            }
                        }
                        if (inq.Count() > 0)
                        {
                            foreach (var temp in inq)
                            {
                                db.DeleteObject(temp);
                            }
                        }
                        if (exq.Count() > 0)
                        {
                            foreach (var temp in exq)
                            {
                                db.DeleteObject(temp);
                            }
                        }
                        db.SaveChanges(false);
                        scope.Complete();
                        db.AcceptAllChanges();
                    }
                }
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }

        //获取准备修改题目的信息
        public UpdateQuestion GetUpdateQuestion(int eid)
        {
            try
            {
                UpdateQuestion question = new UpdateQuestion();
                //var exq = db.Ex_question.Where(a => a.Eid == eid).FirstOrDefault();//这样得来的exq关联信息会空
                //var inq = db.In_question.Where(a => a.Ex_question.Eid == eid).ToList();//这样得来的inq关联信息会空
                var exq = (from a in db.Ex_question
                           where a.Eid == eid
                           select new
                           {
                               a.Chapter,
                               a.Course,
                               a.Econtent,
                               a.Eid,
                               a.Enum,
                               a.Etime,
                               a.Etype,
                               a.Knowledge,
                               a.Teacher,
                               a.TorE
                           }).FirstOrDefault();
                var inq = (from a in db.In_question
                           where a.Ex_question.Eid == eid
                           select new
                           {
                               a.Answer_mode,
                               a.Choice,
                               a.Ex_question,
                               a.Fill,
                               a.Iid,
                               a.Iorder,
                               a.Judge,
                               a.QnA
                           }).ToArray();
                //赋值外表信息
                question.chapter = exq.Chapter;
                question.content = exq.Econtent;
                question.course = exq.Course.Cname;
                question.creator = exq.Teacher.Tname;
                question.eid = exq.Eid;
                question.includeNum = exq.Enum;
                question.knowledge = exq.Knowledge;
                question.time = exq.Etime;
                question.TorE = exq.TorE;
                question.type = exq.Etype;
                //赋值内表信息
                question.inq = new UpdateInQuestion[inq.Count()];//需要根据inq行数新增question.inq数组元素
                for (int i = 0; i < inq.Count(); i++)
                {
                    question.inq[i] = new UpdateInQuestion();//需要根据循环次数来构造question.inq数组元素
                    question.inq[i].iid = inq[i].Iid;
                    question.inq[i].Iorder = inq[i].Iorder;
                    question.inq[i].answerMode = inq[i].Answer_mode;
                    question.inq[i].isNew = false;//标记为不是新增
                    question.inq[i].isDelete = false;//标记为不是删除了的
                    if (inq[i].Answer_mode == "选择题")
                    {
                        question.inq[i].answer = inq[i].Choice.Answer;
                        question.inq[i].Icontent = inq[i].Choice.Ccontent;
                        question.inq[i].isSingle = inq[i].Choice.Issingle;
                        question.inq[i].option1 = inq[i].Choice.Option1;
                        question.inq[i].option2 = inq[i].Choice.Option2;
                        question.inq[i].option3 = inq[i].Choice.Option3;
                        question.inq[i].option4 = inq[i].Choice.Option4;
                        question.inq[i].option5 = inq[i].Choice.Option5;
                        question.inq[i].option6 = inq[i].Choice.Option6;
                        question.inq[i].option7 = inq[i].Choice.Option7;
                        question.inq[i].option8 = inq[i].Choice.Option8;
                        question.inq[i].optionNum = inq[i].Choice.optionNum;
                    }
                    else if (inq[i].Answer_mode == "填空题")
                    {
                        question.inq[i].Icontent = inq[i].Fill.Fcontent;
                        question.inq[i].answer = inq[i].Fill.Answer;
                    }
                    else if (inq[i].Answer_mode == "判断题")
                    {
                        question.inq[i].answer = inq[i].Judge.Answer;
                        question.inq[i].Icontent = inq[i].Judge.Jcontent;
                    }
                    else if (inq[i].Answer_mode == "回答问题")
                    {
                        question.inq[i].answer = inq[i].QnA.Answer;
                        question.inq[i].Icontent = inq[i].QnA.Qcontent;
                    }
                }
                return question;
            }
            catch(Exception e)
            {
                //防止从地址栏输入不存在的id，都赋值为空
                return new UpdateQuestion() { chapter="", content="", course="", creator="", eid=-1, includeNum=0, inq=new UpdateInQuestion[0], knowledge="", time=new DateTime(), TorE="", type=""};
            }
        }

        //修改题目
        public bool UpdateQuestion(UpdateQuestion question)
        {
            try
            {
                //用于新添加项
                In_question inquestion;
                Fill inqFill;
                Choice inqChoice;
                Judge inqJudge;
                QnA inqQna;
                var exq = db.Ex_question.Where(a => a.Eid == question.eid).FirstOrDefault();//这样得来的exq关联信息会空
                //更新外表
                exq.Econtent = question.content;
                exq.Etype = question.type;
                exq.Enum = question.includeNum;
                exq.Chapter = question.chapter;
                exq.Knowledge = question.knowledge;
                exq.TorE = question.TorE;
                db.SaveChanges();
                //更新内表
                if (question.inq != null)
                {
                    for (int i = 0; i < question.inq.Count(); i++)
                    {
                        //删除已有项
                        if (question.inq[i].isDelete)
                        {
                            int iid = question.inq[i].iid;
                            var inq = db.In_question.Where(a => a.Iid == iid).FirstOrDefault();
                            if (question.inq[i].answerMode == "选择题")
                            {
                                var choice = db.Choice.Where(a => a.Iid == inq.Iid).FirstOrDefault();
                                db.DeleteObject(choice);
                            }
                            else if (question.inq[i].answerMode == "填空题")
                            {
                                var fill = db.Fill.Where(a => a.Iid == inq.Iid).FirstOrDefault();
                                db.DeleteObject(fill);
                            }
                            else if (question.inq[i].answerMode == "判断题")
                            {
                                var judge = db.Judge.Where(a => a.Iid == inq.Iid).FirstOrDefault();
                                db.DeleteObject(judge);
                            }
                            else if (question.inq[i].answerMode == "回答问题")
                            {
                                var qna = db.QnA.Where(a => a.Iid == inq.Iid).FirstOrDefault();
                                db.DeleteObject(qna);
                            }
                            db.DeleteObject(inq);
                            db.SaveChanges();
                        }
                        //添加新项
                        else if (question.inq[i].isNew)
                        {
                            inquestion = new In_question();
                            inquestion.Ex_question = exq;
                            inquestion.Iorder = question.inq[i].Iorder;
                            inquestion.Answer_mode = question.inq[i].answerMode;
                            db.AddToIn_question(inquestion);
                            db.SaveChanges();
                            if (question.inq[i].answerMode == "选择题")
                            {
                                inqChoice = new Choice();
                                inqChoice.In_question = inquestion;
                                inqChoice.Answer = question.inq[i].answer;
                                inqChoice.Ccontent = question.inq[i].Icontent;
                                inqChoice.Issingle = question.inq[i].isSingle;
                                inqChoice.Option1 = question.inq[i].option1;
                                inqChoice.Option2 = question.inq[i].option2;
                                inqChoice.Option3 = question.inq[i].option3;
                                inqChoice.Option4 = question.inq[i].option4;
                                inqChoice.Option5 = question.inq[i].option5;
                                inqChoice.Option6 = question.inq[i].option6;
                                inqChoice.Option7 = question.inq[i].option7;
                                inqChoice.Option8 = question.inq[i].option8;
                                inqChoice.optionNum = question.inq[i].optionNum;
                                db.AddToChoice(inqChoice);
                                db.SaveChanges();
                            }
                            else if (question.inq[i].answerMode == "填空题")
                            {
                                inqFill = new Fill();
                                inqFill.In_question = inquestion;
                                inqFill.Fcontent = question.inq[i].Icontent;
                                inqFill.Answer = question.inq[i].answer;
                                db.AddToFill(inqFill);
                                db.SaveChanges();
                            }
                            else if (question.inq[i].answerMode == "判断题")
                            {
                                inqJudge = new Judge();
                                inqJudge.In_question = inquestion;
                                inqJudge.Jcontent = question.inq[i].Icontent;
                                inqJudge.Answer = question.inq[i].answer;
                                db.AddToJudge(inqJudge);
                                db.SaveChanges();
                            }
                            else if (question.inq[i].answerMode == "回答问题")
                            {
                                inqQna = new QnA();
                                inqQna.In_question = inquestion;
                                inqQna.Answer = question.inq[i].answer;
                                inqQna.Qcontent = question.inq[i].Icontent;
                                db.AddToQnA(inqQna);
                                db.SaveChanges();
                            }
                        }
                        //更新已有项
                        else
                        {
                            int iid = question.inq[i].iid;
                            var inq = db.In_question.Where(a => a.Iid == iid).FirstOrDefault();//这样得来的inq关联信息会空
                            inq.Iorder = question.inq[i].Iorder;
                            if (question.inq[i].answerMode == "选择题")
                            {
                                var choice = db.Choice.Where(a => a.Iid == inq.Iid).FirstOrDefault();
                                choice.In_question = inq;
                                choice.Answer = question.inq[i].answer;
                                choice.Ccontent = question.inq[i].Icontent;
                                choice.Issingle = question.inq[i].isSingle;
                                choice.Option1 = question.inq[i].option1;
                                choice.Option2 = question.inq[i].option2;
                                choice.Option3 = question.inq[i].option3;
                                choice.Option4 = question.inq[i].option4;
                                choice.Option5 = question.inq[i].option5;
                                choice.Option6 = question.inq[i].option6;
                                choice.Option7 = question.inq[i].option7;
                                choice.Option8 = question.inq[i].option8;
                                choice.optionNum = question.inq[i].optionNum;
                                db.SaveChanges();
                            }
                            else if (question.inq[i].answerMode == "填空题")
                            {
                                var fill = db.Fill.Where(a => a.Iid == inq.Iid).FirstOrDefault();
                                fill.In_question = inq;
                                fill.Fcontent = question.inq[i].Icontent;
                                fill.Answer = question.inq[i].answer;
                                db.SaveChanges();
                            }
                            else if (question.inq[i].answerMode == "判断题")
                            {
                                var judge = db.Judge.Where(a => a.Iid == inq.Iid).FirstOrDefault();
                                judge.In_question = inq;
                                judge.Jcontent = question.inq[i].Icontent;
                                judge.Answer = question.inq[i].answer;
                                db.SaveChanges();
                            }
                            else if (question.inq[i].answerMode == "回答问题")
                            {
                                var qna = db.QnA.Where(a => a.Iid == inq.Iid).FirstOrDefault();
                                qna.In_question = inq;
                                qna.Answer = question.inq[i].answer;
                                qna.Qcontent = question.inq[i].Icontent;
                                db.SaveChanges();
                            }
                            db.SaveChanges();
                        }
                    }
                }
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }

        //添加新课程
        public bool AddCourse(string newCourse)
        {
            try
            {
                int has = db.Course.Where(a => a.Cname == newCourse).Count();
                if (has > 0)
                {
                    return false;
                }
                Course course = new Course();
                course.Cname = newCourse;
                db.AddToCourse(course);
                db.SaveChanges();
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
            
        }
    }
}
